//
// Created by zxm on 18-5-29.
//

#include "tictoc.h"
#include <ctime>

using namespace std::chrono;

// a wrap of clock function
// return the time duration in ms two different call
long tictoc_ms()
{
    static system_clock::time_point last_timestamp_ms = system_clock::now();// initial

    system_clock::time_point now_timestamp = system_clock::now();
    milliseconds duration = duration_cast<milliseconds>(now_timestamp - last_timestamp_ms);
    last_timestamp_ms = now_timestamp;

    return duration.count();
}

// a wrap of clock function
// return the time duration in us two different call
long tictoc_us()
{
    static system_clock::time_point last_timestamp_us = system_clock::now();// initial

    system_clock::time_point now_timestamp = system_clock::now();
    microseconds duration = duration_cast<microseconds>(now_timestamp - last_timestamp_us);
    last_timestamp_us = now_timestamp;

    return duration.count();
}

// get time from system boot (ms)
long get_steady_clock()
{
    steady_clock::time_point time_point = steady_clock::now();
    return duration_cast<milliseconds>(time_point.time_since_epoch()).count();
}

// get time from 1970-01-01T00:00:00 (ms)
long get_system_clock()
{
    system_clock::time_point time_point = system_clock::now();
    return duration_cast<milliseconds>(time_point.time_since_epoch()).count();
}

// convert steady clock to system clock
// steady clock : time duration from system boot
// system clock : time duration form 1970-01-01T00:00:00
long steady_ns_2_system_ns(unsigned long long steady_time_ns)
{
    static bool first_call = true;
    static long sdy_sys_cnt_diff = 0;

    if (first_call)
    {
        first_call = false;

        // get time duration from 1970-01-01T00:00:00 to system boot
        system_clock::time_point sys_clk = system_clock::now();
        steady_clock::time_point sdy_clk = steady_clock::now();
        auto sys_clk_cnt = duration_cast<nanoseconds>(sys_clk.time_since_epoch()).count();
        auto sdy_clk_cnt = duration_cast<nanoseconds>(sdy_clk.time_since_epoch()).count();
        sdy_sys_cnt_diff = sys_clk_cnt - sdy_clk_cnt;
    }

    return (steady_time_ns + sdy_sys_cnt_diff) / 1000000;
}